<?php
namespace app\http;

use think\worker\Server;
use Workerman\Connection\TcpConnection;

use think\App;
$app = App::getInstance();
$app->initialize();

/**
 * 币种最新数据维护服务
 */
class SymbolWorker extends Server
{
    protected $socket = 'http://0.0.0.0:2388';
    protected $symbols = [];
    protected $connections = [];
    public function onConnect($connection)
    {
        // 新建连接时，将连接保存到连接池中
        $this->connections[$connection->id] = $connection;
    }
    public function onClose($connection)
    {
        // 关闭连接时，将连接从连接池中删除
        unset($this->connections[$connection->id]);
    }
    public function onMessage(TcpConnection $connection,$message)
    {
        if(empty($message)){
            return ;
        }

        $data = json_decode($message, true);
        $symbol = $data['symbol'];
        $time  = $data['time'];

        $send = false;

        if(!isset($this->symbols[$data['symbol']])){
            $this->symbols[$data['symbol']] = [];
        }
        if(!isset($this->symbols[$symbol][$time])){
            $this->symbols[$symbol][$time] = $data['data'];
            $send = true;
        }else{
            $old = $this->symbols[$symbol][$time];
            if($old['pushtime']<$data['data']['pushtime'] || $old['timestamp']<$data['data']['timestamp']){
                $this->symbols[$symbol][$time] = $data['data'];
                $send = true;
            }
        }
        if($send){

            foreach ($this->connections as $id=>$conn) {
                if($id!=$connection->id){
                    $conn->send($message);
                }
            }
        }

    }
}